<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import Project from '@/components/Project/index.vue'
import GisMap from '@/components/GisMap/index.vue'
import Input from '@/components/Input/index.vue'
import Tools from '@/components/Tools/index.vue'
import LayerControl from '@/components/LayerControl/index.vue'
import Promot from '@/components/Promot/index.vue'
import { selectAllRecord, selectInfoByCondition, updateRecord } from '@/api/record'
import Bus from '@/utils/bus'
import { showFailToast, showSuccessToast, showToast } from 'vant'
import { deleteLine, insertLine, selectLineByRecordId } from '@/api/line'
import { updateArea } from '@/api/area'

// 地图实例
const mapRef = ref()
// 所有档案
const recordList = ref<any>([])
// 当前所选档案下的数据
const selRecordData = ref<any>([])
// 所选档案下的所有渲染信息
const currRecordData = ref<any>()
// 当前选中的记录ID
const currentRecordId = ref<number>()
// 当前选中的图层类型
const currentSelectTypes = ref<number[]>([1, 2, 3, 4, 5])

function getRocords() {
  selectAllRecord().then((res: any) => {
    if (res.code === 500) {
      showFailToast(res.message)
    }
    recordList.value = res.data
  })
}

// 处理记录选择
function handleRecordSelected({ recordId, selectTypes }) {
  // 更新工具和底部Promot为最初状态
  Bus.$emit('showLayerControl', true)
  Bus.$emit('refreshTool', true)
  Bus.$emit('showPromot', { show: false })

  currentRecordId.value = recordId
  currentSelectTypes.value = selectTypes
  refreshMapData(recordId, selectTypes)

  // 过滤当前档案下的排查范围
  selRecordData.value = []
  recordList.value.forEach((item) => {
    if (item.id === recordId) {
      selRecordData.value = [item]
    }
  })
}

// 处理图层选择
function handleLayerSelect({ selectTypes }) {
  if (currentRecordId.value) {
    currentSelectTypes.value = selectTypes
    // 调用接口获取数据
    refreshMapData(currentRecordId.value, selectTypes)
  }
}
/**
 * 1 雨水管线  #8D54CF
 * 2 污水管线 #C3170A
 * 3 雨污混接管线 #F17A2F
 */
function getLineColor(type) {
  switch (type) {
    case 1:
      return '#8D54CF'
    case 2:
      return '#C3170A'
    case 3:
      return '#F17A2F'
  }
}
function refreshMapData(recordId: number, selectTypes: number[], searchName: string = '') {
  Bus.$emit('clearSearchValue')
  selectInfoByCondition({
    recordId,
    selectTypes,
    selectName: searchName,
  }).then((res) => {
    // 使用新对象触发响应式更新
    currRecordData.value = { ...res.data }
  })
}
function addPolyline(markerPoslists: any) {
  let lineType: any
  let color: any
  // 虚线/实线(0:虚线,1:实线)
  const isDottedSolid = markerPoslists[1]?.id ? 1 : 0
  const startWellType = markerPoslists[0].wellType
  // 虚线情况
  if (isDottedSolid === 0) {
    lineType = startWellType
  }
  else {
    // 实线情况
    const endWellType = markerPoslists[1].wellType
    if (startWellType === 1 && endWellType === 1) {
      // 雨水管线
      lineType = 1
      color = '#8D54CF'
    }
    else if (startWellType === 2 && endWellType === 2) {
      // 污水管线
      lineType = 2
      color = '#C3170A'
    }
    else {
      // 雨污混接管线
      lineType = 3
      color = '#F17A2F'
    }
  }
  color = getLineColor(lineType)
  const [lng, lat] = markerPoslists[0].coordinates.split(',').map(Number)
  let secondPos: any = []
  if (markerPoslists[1]?.id) {
    secondPos = markerPoslists[1].coordinates.split(',').map(Number)
  }
  else {
    secondPos = [markerPoslists[1].rtkLongitude, markerPoslists[1].rtkLatitude]
  }

  const params = {
    coordinates: [
      [lng, lat],
      secondPos,
    ],
    color,
    createUserId: selRecordData.value[0].createUserId,
    isDottedSolid, // 虚线/实线
    lineType, // 管线类型
    tbSurveyRecordId: markerPoslists[0].tbSurveyRecordId, // 档案ID
  }
  // console.log(params, 'params')

  insertLine(params).then(async (res) => {
    if (res.code === 200) {
      handleLayerSelect({ selectTypes: [1, 2, 3, 4, 5] })
      setTimeout(() => {
        showToast('管线绘制成功')
      }, 500)
    }
  })
}

function onDeleteline(id) {
  // console.log(id, 'id')
  deleteLine(id.id).then(async (res) => {
    if (res.code === 200) {
      handleLayerSelect({ selectTypes: [1, 2, 3, 4, 5] })
      setTimeout(() => {
        showToast('管线删除成功')
      }, 500)
    }
  })
}

// 处理多边形创建
function onPolygonCreated({ updatePolygonObj }) {
  if (!currentRecordId.value) {
    showFailToast('请先选择档案')
    return
  }

  updateArea(updatePolygonObj).then((res) => {
    if (res.code === 200) {
      handleLayerSelect({ selectTypes: currentSelectTypes.value })
      setTimeout(() => {
        showToast('区域绘制成功')
      }, 500)
    }
    else {
      showFailToast(res.message || '区域保存失败')
    }
  })
}

function updatePolygonRange({ updatePolygonObj }) {
  updateRecord(updatePolygonObj).then((res) => {
    if (res.code === 200) {
      handleLayerSelect({ selectTypes: currentSelectTypes.value })
      setTimeout(() => {
        showToast('排查范围绘制成功')
      }, 500)
    }
    else {
      showFailToast(res.message || '区域保存失败')
    }
  })
}

function onSearch(val) {
  refreshMapData(currentRecordId.value, [1, 2, 3, 4, 5], val)
}

// 监听事件
onMounted(() => {
  getRocords()
})

// 清理事件监听
onUnmounted(() => {})
</script>

<template>
  <div class="h-vh w-full overflow-hidden">
    <Project :record-list="recordList" @select-record="handleRecordSelected" />
    <GisMap
      ref="mapRef"
      :record-data="currRecordData"
      :scope-polygon-data="selRecordData"
      @add-polyline="addPolyline"
      @deleteline="onDeleteline"
      @polygon-created="onPolygonCreated"
      @update-polygon-range="updatePolygonRange"
    />
    <Input @search="onSearch" />
    <Tools :map-ref="mapRef" :record-data="currRecordData" :sel-record="selRecordData" />
    <LayerControl @select-record="handleLayerSelect" />
    <Promot :map-ref="mapRef" />
  </div>
</template>

<route lang="json5">
  {
    name: 'map',
    meta: {
      title: '',
      i18n: ''
    },
  }
</route>
